package clientCommunicationHandler;

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;

import org.jboss.netty.channel.Channel;

import ClientLogger.ClientLogger;

import client.TelnetClient;

public class UserInterfaceMsgHandler {
	BackStack stack;
	public UserInterfaceMsgHandler(){
		stack = new BackStack();

	}

	public String parserUserMsg(int userRequest , String[] menuInArray){
		String [] tMenuInArray = menuInArray;
		tMenuInArray = tMenuInArray[userRequest] .split(" ");
		String temp = tMenuInArray[1];
		ClientLogger.clientlogger.info("UserInterFaceMsgAHndler:the command i parsed is "+temp);
		if(temp.equalsIgnoreCase("Logout\n")){
			temp = "logout\n"+TelnetClient.userName+"\n\0\n";
		}
		if(temp.equalsIgnoreCase("Login\n")){
			temp = handleLoginForm();
		}
		if(temp.equalsIgnoreCase("register\n"))
			temp = handleRegisterForm();
		if(temp.equalsIgnoreCase("view_Forums\n")){
			temp = "viewForum\n\0\n";
			TelnetClient.SubForumId = -1;
			stack.addNewCommand(temp);
		}
		if(temp.equalsIgnoreCase("viewThreads")){
			String threadId = tMenuInArray[2].split(":")[0];
			temp = BuildViewThreadMsg(tMenuInArray[2].split(":")[0]);//"viewThread\n"+TelnetClient.SubForumId+"\n"+ tMenuInArray[2].split(":")[0]+"\n\0\n";
			TelnetClient.postId = -1;
			TelnetClient.tempThreadID = Integer.parseInt(threadId);
			stack.addNewCommand(temp);
		} 
		if(temp.equalsIgnoreCase("viewSubForum")||temp.equalsIgnoreCase("viewSubForum\n")){
//			System.out.println("View sub forum id "+ tMenuInArray[2]);
			temp = BuildViewSubForumMsg(tMenuInArray[2].split(":")[0]);//"viewSubForum\n" + tMenuInArray[2].split(":")[0]+"\n\0\n";
			stack.addNewCommand(temp);
			TelnetClient.threadId = -1;
			TelnetClient.tempSubForumID = Integer.parseInt(tMenuInArray[2].split(":")[0]);
		}
		if(temp.equalsIgnoreCase("add\n")||temp.equalsIgnoreCase("add")){
			if(TelnetClient.userName != "guest"){
				TelnetClient.postId = -1;
				temp = handleAddNewMsg();
			}
			else{
				System.out.println("you are not login.\n in order to post you must to login\n redirecting to welcomPage... ");
				TelnetClient.menu = TelnetClient.welcom_page;
				TelnetClient.transmitToServer = false;
			}
		}
		if(temp.equalsIgnoreCase("addPost"))
		{
			temp = handleNewPostMsg(tMenuInArray[2]);
			
		}
		if(temp.equalsIgnoreCase("replay")){
			temp = handleReplayToAPost();
		}

		if(temp.equalsIgnoreCase("back\n")||temp.equalsIgnoreCase("back")){
			temp = handleBackMsg();
		}
		if(temp.equalsIgnoreCase("postID"))
			temp = refreshView();
		if(temp.equalsIgnoreCase("exit\n")||temp.equalsIgnoreCase("exit")){
			temp = "bye\n\0\n";
		}
		
		return temp;

	}

	private String handleNewPostMsg(String postId) {
		ReadNewMsg tMsg = new ReadNewMsg();
		String msg = tMsg.readMsgFromUser();
		String temp = "addPost\n"+TelnetClient.userName+"\n"+msg+"\n"+Integer.toString(TelnetClient.SubForumId)+"\n"
		+Integer.toString(TelnetClient.threadId)+"\n"+postId+"\n\0\n"+
		this.refreshLastViewedThread();
		 return temp;
	}

	private String BuildViewSubForumMsg(String subForumId) {
		TelnetClient.SubForumId = Integer.parseInt(subForumId);
		return "viewSubForum\n" + subForumId+"\n\0\n";
	}

	private String BuildViewThreadMsg(String threadID) {
		return "viewThread\n"+TelnetClient.SubForumId+"\n"+threadID+"\n\0\n";
	}

	private String handleBackMsg() {
		String temp = stack.getLastCommand();
		if(temp.equalsIgnoreCase("")){
			TelnetClient.transmitToServer = false;
		}
		return temp;
		
//		String temp = "";
//		if(TelnetClient.postId > 0){
//			temp  = BuildViewThreadMsg(Integer.toString(TelnetClient.threadId));
//		}
//		else{
//			if(TelnetClient.SubForumId > 0){
//				BuildViewSubForumMsg(Integer.toString(TelnetClient.SubForumId));
//			}
//			else{
//				TelnetClient.menu = TelnetClient.welcom_page;
//				TelnetClient.transmitToServer = false;
//			}
//		}
//		return temp;

	}

	private String handleReplayToAPost() {
		int postId = 0 ; 
//		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String tpostId = null;
		System.out.println("enter post id to reaply to");
		while(tpostId == null){
			try {
				tpostId = TelnetClient.in.readLine();
				postId = Integer.parseInt(tpostId);	
			}
			catch (Exception e) {
				e.printStackTrace();
				System.out.println("post id  must be a number");
				tpostId = null;
			}
		}
		TelnetClient.postId = postId;
		String result = handleAddNewMsg();
		TelnetClient.postId = -1;
		return result;
	}
	
	private String handleAddNewMsg() {
		ReadNewMsg tMsg = new ReadNewMsg();
		String msg = tMsg.readMsgFromUser();
		String temp = ((TelnetClient.threadId < 0) ?"addThread\n"+TelnetClient.userName+"\n"+msg+"\n"+Integer.toString(TelnetClient.SubForumId)+"\n\0\n" +
				this.refreshLastViewedsubForum()
				:"addPost\n"+TelnetClient.userName+"\n"+msg+"\n"+Integer.toString(TelnetClient.SubForumId)+"\n"+Integer.toString(TelnetClient.threadId)+"\n"+
				(TelnetClient.postId > 0 ? TelnetClient.postId:TelnetClient.threadId)+"\n\0\n"+ 
				this.refreshLastViewedThread());

		return temp;
	}
	
	
	private String refreshView(){
		String temp = stack.viewLastCommand();
		if(temp.equalsIgnoreCase("")){
			TelnetClient.transmitToServer = false;
			TelnetClient.menu = TelnetClient.welcom_page;
		}
		return temp;
//		if(TelnetClient.threadId > 0){
//			temp = refreshLastViewedThread();
//		}
//		else{
//			if(TelnetClient.SubForumId > 0){
//				temp = refreshLastViewedsubForum();
//			}
//		}
//		if(temp.equals(""))
//			TelnetClient.transmitToServer = false;
//		return temp;
	}
	/**
	 * @pre TelnetClient.subForumId > 0 ; 
	 * @return the command to watch the last sub forum the user was in 
	 */
	private String refreshLastViewedsubForum(){
		return "viewSubForum\n"+Integer.toString(TelnetClient.SubForumId)+"\n\0\n";
	}
	/**
	 * @pre TelnetClient.subForumId > 0 && TelnetClient.threadId > 0; 
	 * @return the command to watch the last sub forum the user was in 
	 */
	private String refreshLastViewedThread(){
		return "viewThread\n"+TelnetClient.SubForumId+"\n"+TelnetClient.threadId +"\n\0\n";
	}
	
	private String readUserName(BufferedReader in){
		System.out.println("enter your user name:");
		String tUserName = null;
		while(tUserName == null){
			try {
				tUserName = in.readLine();
				if(tUserName.equals("")){
					tUserName = null;
					System.out.println("invalid user name please re-enter your user name");		
				}
			} catch (IOException e) {
				e.printStackTrace();
				tUserName = null;
			}
		}
		//save the temporary user name,for future management.
		TelnetClient.tempUserName = tUserName;
		return tUserName;
		
	}

	
	private String readUserPass(BufferedReader in){
		Console c = System.console();
		UserProxyPasswordReader pass = new UserProxyPasswordReader();
		pass.setBuffer(in);
		pass.setConsole(c);
		return pass.readPassword();
	}
	
	private String handleLoginForm() {
//		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String tUserName = readUserName(TelnetClient.in);
		String tPass = readUserPass(TelnetClient.in);
		String result = "login\n"+tUserName+"\n"+tPass+"\n\0\n"+refreshView();
		if(TelnetClient.SubForumId < 0)
			ClientServerMsgHandler.buildMenu = true;
		else{
			ClientServerMsgHandler.buildMenu = false;
			result += refreshView();
		}
		return result;
	}
	

	private  String handleRegisterForm() {
//		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String tUserName = readUserName(TelnetClient.in);
		String tPass = readUserPass(TelnetClient.in);
		return "register\n"+tUserName+"\n"+tPass+"\n\0\n";
	}

}
